//
//  AFNetworkTools+OAuth.swift
//  ShangHaiWeiBo
//
//  Created by 蔡杰 on 16/2/27.
//  Copyright © 2016年 蔡杰. All rights reserved.
//

import Foundation
extension AFNworkTools {
    
    /// 返回身份验证 URL
    /**
    1. 没有参数，只有返回值的函数，在调用的时候，有一个 ()
    2. 使用计算型属性，直接返回某一个类型的结果
    3. 计算型属性不能接参数
    4. 阅读的语义会更好！
    */
    //func oauthURL() -> NSURL {
    var oauthURL: NSURL {
        
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(AppKey)&redirect_uri=\(redirectUri)"
        
        return NSURL(string: urlString)!
    }
    func loadAccsessToken(code:String, finished:([String : AnyObject]?) ->()){
        
        let urlString = "https://api.weibo.com/oauth2/access_token"
        let params = ["client_id":AppKey,
            "client_secret":AppSecret,
            "grant_type":"authorization_code",
            "code":code,
            "redirect_uri":redirectUri]
        
        request(.POST, URLString: urlString, parameters: params) {[weak self] (result) -> () in
            //取出token的结果
            print(result)
            guard let result = result,
                let accsessToKen = result["access_token"] as? String,
                let uid = result["uid"] as? String else {
                    
                    finished(nil)
                    return
                    
            }
            self?.loadUser(accsessToKen, uid: uid, finished: { (userDict) -> () in
                print(accsessToKen,uid)
                guard var userDict = userDict else {
                    
                    finished(nil)
                    
                    return
                }
                
                
                for (k,v) in result {
                    
                    userDict[k] = v
                }
                
                finished(userDict)
            })
        }
    }
    
}

